
import sys
import os
sys.path.append(os.getcwd())
import time
from util.protocol import *
import util.tool as tool
import struct

def make698(addr:str, addrType:str, apdu:str):
    prot = Protocol()
    return prot.set_address(addr).set_address_type(addrType).set_link_user_data(apdu).format_frame_string()
def getApdu(frame:str):
    prot = Protocol()
    return prot.parser_frame(frame).get_link_user_data()

def GetVarLenStr(length):
    buffer = []
    if (length >= 0x80):
        buffer.append(0x81)
        if (length > 255):
            buffer[0] = (buffer[0] + 1) & 0xFF
            buffer.append((length >> 8) & 0xFF)
            buffer.append(length & 0xFF)
        else:
            buffer.append(length & 0xFF)
        #todo
    else:
        buffer.append(length & 0xFF)
    a = ""
    for i in buffer:
        b = tool.Dec2HexStr(i)
        print("b=",b)
        a = a + b
        
    return a

def cosem_bin2_unit(dataStr, index, size):
    val = 0
    for i in range(size):
        val <<= 8
        val += tool.HexStr2DecInt(dataStr[(i + index) * 2:(i + index) * 2 + 2])
    return val

def ParseVarLength(dataStr):
    num = 0
    len_size = 0
    aa = dataStr[0:2]
    if ((tool.HexStr2DecInt(aa) & 0x80) > 0):
        #num = Common698.cosem_bin2_unit(buffer, index + 2, buffer[index + 1] & 0x7F);
        #len_size = (buffer[index + 1] & 0x7F) + 1;
        num = cosem_bin2_unit(dataStr, 1, tool.HexStr2DecInt(aa) & 0x7F)
        len_size = (tool.HexStr2DecInt(aa) & 0x7F) + 1
    else:
        #num = buffer[index + 1];
        #len_size = 1;
        num = tool.HexStr2DecInt(aa)
        len_size = 1
    return num,len_size



def GetDataType(dataStr, begin):
    if(begin + 2)>len(dataStr):
        return
    return tool.HexStr2DecInt(dataStr[begin:begin + 2])


class DATA_TYPE:
        DT_NULL = 0
        DT_ARRAY = 1
        DT_STRUCTURE = 2
        DT_BOOL = 3
        DT_BIT_STRING=4
        DT_DOUBLELONG = 5
        DT_DOUBLELONGUNSIGNED = 6
        DT_OCTETSTRING = 9
        DT_VISIBLESTRING = 10
        DT_UTF8STRING = 12
        DT_INTEGER = 15
        DT_LONG = 16
        DT_UNSIGNED = 17
        DT_LONGUNSIGNED = 18
        DT_LONG64 = 20
        DT_LONG64UNSIGNED = 21
        DT_ENUM = 22
        DT_FLOAT32 = 23
        DT_FLOAT64 = 24
        DT_DATE_TIME = 25
        DT_DATE = 26
        DT_TIME = 27
        DT_DATE_TIME_S = 28
        DT_OI = 80
        DT_OAD = 81
        DT_ROAD = 82
        DT_OMD = 83
        DT_TI = 84
        DT_TSA = 85
        DT_MAC = 86
        DT_RN = 87
        DT_REGION = 88
        DT_SCALER_UNIT = 89
        DT_RSD = 90
        DT_CSD = 91
        DT_MS = 92
        DT_SID = 93
        DT_SID_MAC = 94
        DT_COMDCB = 95
        DT_RCSD = 96

        DT_STRUCTURE_UINT32 = 210#为虚拟表数据源中的需量数据扩展
        DT_STRUCTURE_INT32 = 211
        DT_STRUCTURE_INT24 = 212
        DT_INT24 = 213
        DT_DATETIME = 214
        DT_LOADRECORD12_VAF = 215
        DT_LOADRECORD12_P = 216

        TRANSPARENT = 255

def En_TSA(addr_str):
    a = addr_str
    return a

def De_TSA(dataStr):
    cnt = (tool.HexStr2DecInt(dataStr[0:2]) & 0x0F) + 1
    addr_str = dataStr[2:2 + cnt * 2]
    return addr_str

def De_TSA_Data(dataStr):
    type = dataStr[0:2]
    cnt = tool.HexStr2DecInt(dataStr[2:4])
    addr_str = dataStr[4: 4 + cnt * 2]
    addr_cnt = (tool.HexStr2DecInt(addr_str[0:2]) & 0x0F) + 1
    return 1 + 1 + 1 + addr_cnt,De_TSA(addr_str)

def En_Null():
    return ""

def De_Null(dataStr):
    return "NULL"

def De_Null_Data(dataStr):
    type = dataStr[0:2]
    return 1,De_Null(dataStr[2:])

def En_OAD(oadStr):
    return oadStr

def De_OAD(dataStr):
    return dataStr[0:8]

def De_OAD_Data(dataStr):
    type = dataStr[0:2]
    return 5,De_OAD(dataStr[2:])

def En_VisibleStr(str):
    return ''.join(format(ord(c), '02x') for c in str)
def De_VisibleStr(dataStr):
    ascii_string = ''.join(chr(int(dataStr[i:i+2], 16)) for i in range(0, len(dataStr), 2))
    return ascii_string
def De_VisibleStr_Data(dataStr):
    type = dataStr[0:2]
    #cnt = tool.HexStr2DecInt(dataStr[2:4])
    cnt,cntLen = ParseVarLength(dataStr[2:])
    #print("cnt:", cnt)
    return (1+cntLen+cnt),De_VisibleStr(dataStr[2*(1+cntLen):2*(1+cntLen)+cnt*2])

def En_OctStr(str):
    return str
def De_OctStr(dataStr):
    return dataStr
def De_OctStr_Data(dataStr):
    type = dataStr[0:2]
    #cnt = tool.HexStr2DecInt(dataStr[2:4])
    cnt,cntLen = ParseVarLength(dataStr[2:])
    #print("cnt:", cnt)
    return (1+cntLen+cnt),De_OctStr(dataStr[2*(1+cntLen):2*(1+cntLen)+cnt*2])

def En_Enum(num):
    return tool.Dec2HexStr(num)
def De_Enum(dataStr):
    return tool.HexStr2DecInt(dataStr)
def De_Enum_Data(dataStr):
    type = dataStr[0:2]
    enum = dataStr[2:4]
    return 2, De_Enum(enum)

def En_DoubleLong(num):
    # Convert the integer to 4 bytes
    bytes_representation = num.to_bytes(4, byteorder='big',signed=True)  # Use 'big' for big-endian
    # Convert bytes to a hexadecimal string
    hex_string = bytes_representation.hex()
    print("Hexadecimal string:", hex_string)
    return hex_string

def De_DoubleLong(hex_string):
    #  Convert the hexadecimal string to bytes
    bytes_representation = bytes.fromhex(hex_string)
    # Convert bytes to a signed integer
    integer_value = int.from_bytes(bytes_representation, byteorder='big', signed=True)
    print("Signed integer:", integer_value)
    return integer_value

def De_DoubleLong_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:10]
    return 5, De_LongUnsigned(num)

def En_Long(num):
    packed_short = struct.pack('>h', num) # '>h' indicates a 16-bit signed short in big-endian
    hex_string = packed_short.hex()
    print("Hexadecimal string:", hex_string)
    return hex_string

def De_Long(hex_string):
    #  Convert the hexadecimal string to bytes
    bytes_representation = bytes.fromhex(hex_string)
    # Convert bytes to a signed integer
    integer_value = struct.unpack('>h', bytes_representation)[0]
    print("Signed short:", integer_value)
    return integer_value

def De_Long_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:6]
    return 3, De_Long(num)

def En_Long64(num):
    packed_short = struct.pack('>q', num) # '>h' indicates a 16-bit signed short in big-endian
    hex_string = packed_short.hex()
    print("Hexadecimal Long64 string:", hex_string)
    return hex_string

def De_Long64(hex_string):
    #  Convert the hexadecimal string to bytes
    bytes_representation = bytes.fromhex(hex_string[0:16])
    # Convert bytes to a signed integer
    integer_value = struct.unpack('>q', bytes_representation)[0]
    print("Long64:", integer_value)
    return integer_value

def De_Long64_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:18]
    return 9, De_Long64(num)

def En_LongUnsigned(num):
    return tool.int_to_unsigned_hex(num)

def De_LongUnsigned(dataStr):
    num = int(dataStr, 16)
    return num

def De_LongUnsigned_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:6]
    return 3, De_LongUnsigned(num)

def En_DoubleLongUnsigned(num):
    return tool.int_to_unsigned_hex(num, 8)

def De_DoubleLongUnsigned(dataStr):
    num = int(dataStr, 16)
    return num

def De_DoubleLongUnsigned_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:10]
    # print("num",num)
    return 5, De_DoubleLongUnsigned(num)

def En_Unsigned(num):
    return tool.Dec2HexStr(num)

def De_Unsigned(dataStr):
    num = int(dataStr, 16)
    return num

def De_Unsigned_Data(dataStr):
    type = dataStr[0:2]
    num = dataStr[2:4]
    return 2, De_Unsigned(num)

#输入格式 20240517000000
def En_DateTimeS(tm:str):
    st =  ""
    num = hex(int(tm[:4])).replace("0x","")
    if len(num)%2:
        num = "0"+num
    st =  st +f"{num}"
    for i in range(4, len(tm), 2):
        st += tool.ByteToHexStr(int(tm[i:i+2]))
        if len(num)%2:
            num = "0"+num
        # st =  st +f"{num}"
    return st
def En_DateTime(tm:str):
    st = ""
    le = len(tm)
    num = hex(int(tm[:4])).replace("0x","")
    if len(num)%2:
        num = "0"+num
    st =  st +f"{num}"
    for i in range(4, le - 4 , 2):
        st += tool.ByteToHexStr(int(tm[i:i+2]))
        if len(num)%2:
            num = "0"+num
    num = hex(int(tm[le - 4:])).replace("0x","")
    zero = 4 - len(num)
    st = st + "0"*zero + num
    return st
def De_DateTimeS(data:str):
    st = ""
    num = str(int(data[:4],16))
    if len(num)%2:
        num = "0"+num
    st =  st +f"{num}"
    for i in range(4, len(data), 2):
        num = str(int(data[i:i+2],16))
        if len(num)%2:
            num = "0"+num
        st =  st +f"{num}"
    return st
def De_DateTimeS_Data(dataStr):
    type = dataStr[:2]
    data = dataStr[2:16]
    return int(len(data)/2 + 1), De_DateTimeS(data)


def De_Array_Data(dataStr):
    dic = {}
    type = dataStr[0:2]
    num = tool.HexStr2DecInt(dataStr[2:4])
    pos = 4
    lens = 2
    for i in range(num):
        datatype = GetDataType(dataStr, pos)
        if(datatype == DATA_TYPE.DT_ARRAY or datatype == DATA_TYPE.DT_STRUCTURE):
            cnt, lenght, data, dictin = JudgmentDataType(dataStr[pos:])
            DictionaryDataProcessing(datatype, dictin, dic, i)
        else:
        
            lenght, data = JudgmentDataType(dataStr[pos:])
            DictionaryDataProcessing(datatype, data, dic, i)
        lens = lens + lenght
        pos = pos + lenght * 2
        
    return num, int(lens), dataStr[4:pos], dic
def De_Struct_Data(dataStr):
    dic = {}
    type = dataStr[0:2]
    num = tool.HexStr2DecInt(dataStr[2:4])
    pos = 4
    lens = 2
    
    for i in range(num):
        datatype = GetDataType(dataStr, pos)
        if(datatype == DATA_TYPE.DT_ARRAY or datatype == DATA_TYPE.DT_STRUCTURE):
            cnt, lenght, data, dictin = JudgmentDataType(dataStr[pos:])
            DictionaryDataProcessing(datatype, dictin, dic, i)
        else:
        
            lenght, data = JudgmentDataType(dataStr[pos:])
            DictionaryDataProcessing(datatype, data, dic, i)
        lens = lens + lenght
        pos = pos + lenght * 2
        
    return num, int(lens), dataStr[4:pos], dic
def DictionaryDataProcessing(str:int, data, dic:dict,i:int):
    Dic_data={}
    Dic_data[str] = data
    dic[i] = Dic_data 
    return dic
def JudgmentDataType(dataStr):
    match int(dataStr[0:2],16):
        case DATA_TYPE.DT_NULL:
            return De_Null_Data(dataStr)
        case DATA_TYPE.DT_VISIBLESTRING:
            return De_VisibleStr_Data(dataStr)
        case DATA_TYPE.DT_ENUM:
            return De_Enum_Data(dataStr)
        case DATA_TYPE.DT_UNSIGNED:
            return De_Unsigned_Data(dataStr)
        case DATA_TYPE.DT_LONGUNSIGNED:
            return De_LongUnsigned_Data(dataStr)
        case DATA_TYPE.DT_ARRAY:
            return De_Array_Data(dataStr)
        case DATA_TYPE.DT_OCTETSTRING:
            return De_OctStr_Data(dataStr)
        case DATA_TYPE.DT_DATE_TIME_S:
            return De_DateTimeS_Data(dataStr)
        case DATA_TYPE.DT_STRUCTURE:
            return De_Struct_Data(dataStr)
        case DATA_TYPE.DT_DOUBLELONGUNSIGNED:
            return De_DoubleLongUnsigned_Data(dataStr)
        case DATA_TYPE.DT_DOUBLELONG:
            return De_DoubleLong_Data(dataStr)
        case DATA_TYPE.DT_LONG:
            return De_Long_Data(dataStr)
        case DATA_TYPE.DT_OCTETSTRING:
            return De_OctStr_Data(dataStr)
        case DATA_TYPE.DT_LONG64:
            return De_Long64_Data(dataStr)
        case DATA_TYPE.DT_TSA:
            return De_TSA_Data(dataStr)
        case DATA_TYPE.DT_OAD:
            return De_OAD_Data(dataStr)
        
        # case DATA_TYPE.DT_UNSIGNED:
            # return (dataStr)
def JugementDatatypePos(data):
    match int(data[0:2],16):
        case DATA_TYPE.DT_DATE_TIME_S:
            return 8*2
        case DATA_TYPE.DT_BOOL:
            return 2*2
def En_Data(type:int, origStr:str, dataCnt = 0):
    if (DATA_TYPE.DT_UNSIGNED == type):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_LONGUNSIGNED == type):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_VISIBLESTRING == type):
        return tool.Dec2HexStr(type) + tool.Dec2HexStr(int(len(origStr) / 2)) + origStr
    elif (DATA_TYPE.DT_ENUM == type):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_DATE_TIME_S == type):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_ARRAY == type):
        return tool.Dec2HexStr(type) + tool.Dec2HexStr(dataCnt) + origStr
    elif (DATA_TYPE.DT_STRUCTURE == type):
        return tool.Dec2HexStr(type) + tool.Dec2HexStr(dataCnt) + origStr
    elif (DATA_TYPE.DT_DOUBLELONGUNSIGNED == type):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_NULL == type):
        return "00"
    elif (DATA_TYPE.DT_DOUBLELONG):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_LONG):
        return tool.Dec2HexStr(type) + origStr
    elif (DATA_TYPE.DT_OCTETSTRING):
        return tool.Dec2HexStr(type) + GetVarLenStr(int(len(origStr) / 2)) + origStr
    
    return ""
def De_Data(dataStr):
    type = GetDataType(dataStr, 0)
    lens=0
    data=""
    if (DATA_TYPE.DT_UNSIGNED == type):
        lens,data = De_Unsigned_Data(dataStr)
    elif (DATA_TYPE.DT_LONGUNSIGNED == type):
        lens,data = De_LongUnsigned_Data(dataStr)
    elif (DATA_TYPE.DT_VISIBLESTRING == type):
        lens,data = De_VisibleStr_Data(dataStr)
    elif (DATA_TYPE.DT_ENUM == type):
        lens,data = De_Enum_Data(dataStr)
    elif (DATA_TYPE.DT_DATE_TIME_S == type):
        lens,data = De_DateTimeS_Data(dataStr)
    elif (DATA_TYPE.DT_ARRAY == type):
        num, lens, data, dic = De_Array_Data(dataStr)
        return type,lens,data,dic,num
    elif (DATA_TYPE.DT_STRUCTURE == type):
        num, lens, data, dic = De_Struct_Data(dataStr)
        return type,lens,data,dic,num
    elif (DATA_TYPE.DT_DOUBLELONGUNSIGNED == type):
        lens,data = De_DoubleLongUnsigned_Data(dataStr)
    elif (DATA_TYPE.DT_NULL == type):
        lens,data = De_Null_Data(dataStr)
    elif (DATA_TYPE.DT_DOUBLELONG == type):
        lens,data = De_DoubleLong_Data(dataStr)
    elif (DATA_TYPE.DT_LONG == type):
        lens,data = De_Long_Data(dataStr)
    elif (DATA_TYPE.DT_OCTETSTRING == type):
        lens,data = De_OctStr_Data(dataStr)
    elif (DATA_TYPE.DT_LONG64 == type):
        lens,data = De_Long64_Data(dataStr)
    elif (DATA_TYPE.DT_TSA == type):
        lens,data = De_TSA_Data(dataStr)
    elif (DATA_TYPE.DT_OAD == type):
        lens,data = De_OAD_Data(dataStr)
    return type,lens, data,"",""

def De_GetResult(dataStr):
    lens:int = 0
    choice = dataStr[0:2]
    data = ""
    dar = ""
    if (choice == "00"):
        lens = 2
        dar = dataStr[2:4]
    else:
        type,lens,data,_,_ = De_Data(dataStr[2:])
        lens = lens + 1
        if (type == DATA_TYPE.DT_ARRAY or type == DATA_TYPE.DT_STRUCTURE):
            a,b,c,d,_ = De_Data(dataStr[2:])
            data = d
    pos = lens*2
    return lens, dataStr[0:int(pos)],data,dar
def De_FactoryVersion(data):
    dic={}
    dic["厂商代码"]=De_VisibleStr(data[:8])
    # dic["软件版本号"] = 
def De_A_ResultNormal(dataStr):
    lens = 0
    oad = ""
    getResult = ""
    oad = dataStr[0:8]
    lens = 4
    ll,getResult,_,_ = De_GetResult(dataStr[8:])
    lens = ll + 4
    return lens, oad, getResult, dataStr[0:int(lens*2)]

def De_A_RecordRow(dataStr, cnt):
    datas = []
    pos = 0
    lens = 0
    for i in range(cnt):
        type,ll,data,dic,num = De_Data(dataStr[pos:])
        # print("De_A_RecordRow type:",type)
        # print("De_A_RecordRow data:",data)
        # print("De_A_RecordRow dic:",dic)
        # print("De_A_RecordRow num:",num)
        #print("De_A_RecordRow, ll type:", (ll))
        datas.append(dataStr[pos:pos + int(ll) * 2])
        
        pos = pos + int(ll) * 2
        lens = lens + ll
        # print("De_A_RecordRow, end:",pos)
    
    return lens, datas, dataStr[0: pos]
def De_A_RecordR(dataStr, cnt):
    datas = []
    pos = 0
    lens = 0
    result = []
    for i in range(cnt):
        type,ll,data,dic,num = De_Data(dataStr[pos:])
        # print("De_A_RecordRow type:",type)
        # print("De_A_RecordRow data:",data)
        # print("De_A_RecordRow dic:",dic)
        # print("De_A_RecordRow num:",num)
        if dic:
            result.append(dic)
        elif data:
            result.append(data)

        #print("De_A_RecordRow, ll type:", (ll))
        datas.append(dataStr[pos:pos + int(ll) * 2])
        
        pos = pos + int(ll) * 2
        lens = lens + ll
        # print("De_A_RecordRow, end:",pos)
    
    return lens, datas, dataStr[0: pos], result

def Dec_A_ResultRecord(dataStr):
    dic = {}
    dic["oad"] = dataStr[:8]
    pos = 8
    ll, csds, rcsd = De_RCSD(dataStr[pos:])
    pos = pos + int(ll) * 2
    dic["choice"] = dataStr[pos:pos + 2]
    pos += 2
    if dic["choice"] == "01":
        dic["data"] = dataStr[pos:]
        dic["num"] = dataStr[pos:pos+2]
    else:
        dic["data"] = dataStr[pos:pos+2]
    return dic
    
def De_A_ResultRecord(dataStr):
    oad = ""
    rcsd = ""
    choice = ""
    dar = ""
    A_RecordRowStrList = []

    lens = 0
    pos = 0
    oad = dataStr[0:8]
    lens = lens + 4
    pos = pos + 8
    ll, csds, rcsd = De_RCSD(dataStr[pos:])
    col = len(csds)
    lens = lens + ll
    pos = pos + int(ll) * 2
    choice = dataStr[pos:pos + 2]
    lens = lens + 1
    pos = pos + 2
    if (choice == "00"):
        dar = dataStr[pos:pos + 2]
        lens = lens + 1
        pos = pos + 2
        return lens, oad, rcsd, dar, A_RecordRowStrList, dataStr[0:pos]
    else:
        cnt = tool.HexStr2DecInt(dataStr[pos:pos+2])
        # print("De_A_ResultRecord, row:", cnt)
        lens = lens + 1
        pos = pos + 2
        for i in range(cnt):
            # print("De_A_ResultRecord, row idx:", i)
            ll, datas, A_rec_str = De_A_RecordRow(dataStr[pos:], col)
            # print("De_A_ResultRecord, De_A_RecordRow:", A_rec_str)
            A_RecordRowStrList.append(A_rec_str)
            lens = lens + int(ll)
            pos = pos + int(ll) * 2
    
        return lens,oad, rcsd, dar, A_RecordRowStrList, dataStr[0:pos]

def Get_Column_Val_From_A_ResultRecord(dataStr:str,oadStr:str):
    colVals = []
    oad = ""
    rcsd = ""
    choice = ""
    dar = ""
    A_RecordRowStrList = []

    lens = 0
    pos = 0
    oad = dataStr[0:8]
    lens = lens + 4
    pos = pos + 8
    ll, csds, rcsd = De_RCSD(dataStr[pos:])
    col = len(csds)
    if (col <= 0):
        return colVals,choice,dar
    colIdx0 = 0
    colIdx1 = -1
    hasOad = False
    for i,csd in enumerate(csds):
        _,moad,moads,_ = De_CSD(csd)
        if (oadStr == moad):
            colIdx0 = i
            hasOad = True
            break
        else:
            if not moads:
                continue
            else:
                for j, noad in enumerate(moads):
                    if (oadStr == noad):
                        colIdx0 = i
                        colIdx1 = j
                        hasOad = True
                        break
                    else:
                        continue
                if (hasOad):
                    break
                else:
                    continue
    if (hasOad == False):
        return colVals,choice,dar

    lens = lens + ll
    pos = pos + int(ll) * 2
    choice = dataStr[pos:pos + 2]
    lens = lens + 1
    pos = pos + 2
    if (choice == "00"):
        dar = dataStr[pos:pos + 2]
        lens = lens + 1
        pos = pos + 2
        return colVals, choice,dar
    else:
        cnt = tool.HexStr2DecInt(dataStr[pos:pos+2])
        # print("Get_Column_Data_From_A_ResultRecord, row:", cnt)
        lens = lens + 1
        pos = pos + 2
        for i in range(cnt):
            # print("Get_Column_Data_From_A_ResultRecord, row idx:", i)
            ll, datas, A_rec_str = De_A_RecordRow(dataStr[pos:], col)
            if (colIdx1 >= 0):
                item = datas[colIdx0]
                typer,llr,data_r,dic_r,num_r = De_Data(item)
                if not num_r or colIdx1 >= num_r or not dic_r:
                    colVals.append("")
                else:
                    colVals.append(dic_r[colIdx1])
            else:
                t,l,d,dc,n = De_Data(datas[colIdx0])
                if not dc:
                    colVals.append(d)
                else:
                    colVals.append(dc)
                
                
            # print("Get_Column_Data_From_A_ResultRecord, De_A_RecordRow:", A_rec_str)
            A_RecordRowStrList.append(A_rec_str)
            lens = lens + int(ll)
            pos = pos + int(ll) * 2
    
        return colVals,choice,dar

def En_ROAD(oad:str, oads:list):
    a = oad + tool.Dec2HexStr(len(list))
    for i in list:
        a = a + i
    return a

def De_ROAD(data:str):
    oad = ""
    oads = []
    oad = data[0:8]
    cnt = tool.HexStr2DecInt(data[8:10])
    lens = 4 + 1
    for i in range(cnt):
        oads.append(data[10 + i * 8 : 10 + i * 8 + 8])
        lens = lens + 4
    return lens,oad,oads,data[0:lens * 2]

def En_CSD(oad:str, road_data_str:str):
    if (oad):
        return tool.Dec2HexStr(0) + oad
    elif(road_data_str):
        return tool.Dec2HexStr(1) + road_data_str
    else:
        return ""

def De_CSD(data:str):
    choice = tool.HexStr2DecInt(data[0:2])
    lens = 1
    if (choice == 0):
        return 5,data[2:10],[],data[0:10]
    elif (choice == 1):
        ll,oad,oads,_ =  De_ROAD(data[2:])
        lens = lens + ll
        return lens,oad,oads,data[0:lens * 2]
    return 0,"",[],""

def En_RCSD(csd_str_list:list):
    a = ""
    for i in csd_str_list:
        a = a + i
    a = tool.Dec2HexStr(len(csd_str_list)) + a
    return a

def De_RCSD(rcsd_str):
    cnt = tool.HexStr2DecInt(rcsd_str[0:2])
    csds = []
    pos = 2
    for i in range(cnt):
        ll, oad, oads,_ = De_CSD(rcsd_str[pos:])
        csds.append(rcsd_str[pos:pos + int(ll) * 2])
        pos = pos + int(ll) * 2
    return int(pos / 2), csds,rcsd_str[0:int(pos)]
            
def JugementCommonDatatype(data:str):
    Datatype = tool.HexStr2DecInt(data[:2])
    if(Datatype == DATA_TYPE.DT_ARRAY or Datatype == DATA_TYPE.DT_STRUCTURE):
        cnt, lenght, data, dictin = JudgmentDataType(data)
        return dictin
    else:
        lenght, data = JudgmentDataType( data)
        return data




if __name__=="__main__":
    s = "20240517000000"
    se=En_DateTimeS(s)
    see=De_DateTimeS(se)
    print(se)
    print(see)